<template>
  <el-header>
    <div class="el-header-title">
      <img class="el-header-logo" :src="logoSrc" height="35" width="147" />
    </div>
    <el-menu
      v-if="!isOnlyNavLeft"
      @select="$emit('setEnableSetMenuLeft', true)"
      :router="true"
      :default-active="activePath"
      mode="horizontal"
      background-color="#545c64"
      text-color="#fff"
      active-text-color="#ffd04b"
    >
      <wrapper-menu-item :navList="navList" :isRecursive="isOnlyNavTop"></wrapper-menu-item>
    </el-menu>
    <el-dropdown @command="handleCommand" trigger="click" placement="bottom-end">
      <div class="el-dropdown-link">
        <img class="mgr5" :src="userSrc" height="24" width="24" />
        {{ username }}
      </div>
      <template #dropdown>
        <el-dropdown-menu>
          <el-dropdown-item command="changePassword">修改密码</el-dropdown-item>
          <el-dropdown-item command="logout">退出登录</el-dropdown-item>
        </el-dropdown-menu>
      </template>
    </el-dropdown>
  </el-header>

  <!--修改密码弹框-->
  <base-dialog ref="dialog" title="修改密码" :dialogId="dialogId" @dialogConfirm="handleChangePassword" @dialogClose="hideDialog">
    <div class="base-dialog-container">
      <el-form :model="formData" :rules="formRules" ref="form" label-width="80px">
        <el-form-item label="原始密码" prop="password">
          <el-input
            maxlength="20"
            type="password"
            placeholder="请输入原始密码"
            v-model.trim="formData.password"
            clearable
            onpaste="return false"
          />
        </el-form-item>
        <el-form-item label="新密码" prop="modifyPassword">
          <el-input
            maxlength="20"
            type="password"
            placeholder="请输入新密码"
            v-model.trim="formData.modifyPassword"
            clearable
            onpaste="return false"
          />
        </el-form-item>
        <el-form-item label="确认密码" prop="modifyPasswordRepeat">
          <el-input
            maxlength="20"
            type="password"
            placeholder="请再次输入新密码"
            v-model.trim="formData.modifyPasswordRepeat"
            clearable
            onpaste="return false"
          />
        </el-form-item>
      </el-form>
    </div>
  </base-dialog>
</template>

<script>
  export default {
    inheritAttrs: false
  }
</script>

<script setup>
  import {useStore} from 'vuex';
  import SHA256 from 'js-sha256';
  import useUserInfo from '@c/useUserInfo';
  import useDialog from '@c/useDialog';
  import WrapperMenuItem from './WrapperMenuItem';
  import logoSrc from '@a/images/layout/logo.png';
  import userSrc from '@a/images/layout/user.png';
  import {ref, reactive, getCurrentInstance, toRefs} from 'vue';

  const {proxy} = getCurrentInstance();
  const {username, userId, logout, isOnlyNavTop, isOnlyNavLeft} = useUserInfo(proxy);
  const {dialogId, showDialog, hideDialog} = useDialog();
  defineEmits(['toggleCollapse', 'setEnableSetMenuLeft']);
  const props = defineProps(['navList', 'path']);
  const {path} = toRefs(props);
  const store = useStore();
  const activePath = ref(store.state.isOnlyNavTop ? path.value[path.value.length - 1] : path.value[0]);
  const formData = reactive({
    password: '',
    modifyPassword: '',
    modifyPasswordRepeat: ''
  });
  const formRules = reactive({
    password: [
      {
        required: true,
        trigger: 'blur',
        fieldType: '原始密码',
        validator: proxy.$validator.password
      }
    ],
    modifyPassword: [{required: true, trigger: 'blur', fieldType: '新密码', validator: proxy.$validator.password}],
    modifyPasswordRepeat: [
      {
        required: true,
        trigger: 'blur',
        fieldType: '确认密码',
        validator: (rule, value, callback) => {
          rule.newPassword = formData.modifyPassword;
          proxy.$validator.password(rule, value, callback);
        }
      }
    ]
  });

  const toggleCollapse = () => proxy.$emit('toggleCollapse');
  const handleCommand = command => {
    if (command === 'logout') handleLogout();
    if (command === 'changePassword') dialogId.value = Date.now();
  };
  // 退出登录
  const handleLogout = async () => {
    const res = await proxy.$api.login.loginOut();
    if (res.status === 200) {
      logout('注销成功', 'success');
    } else {
      proxy.$message.error('注销失败');
    }
  };
  // 确认修改密码
  const dialog = ref(null);
  const handleChangePassword = () => {
    // 子组件方法的调用（子组件ref="form"）可以用2种方式：1. const form = ref(null); form.value.method() 2. this.$refs.form
    // 子组件方法调用的第1种方式
    proxy.$refs.form.validate(async valid => {
      if (!valid) return;
      dialog.value.loadingOpen();
      const params = {
        username: username.value,
        id: userId.value,
        password: SHA256.hmac(username.value, formData.password.value),
        modifyPassword: SHA256.hmac(username.value, formData.modifyPassword.value)
      };
      const res = await proxy.$api.login.changePassword(params);
      // 子组件方法调用的第2种方式
      dialog.value.loadingClose();
      if (res.status === 200) {
        hideDialog();
        logout('密码修改成功，需要重新登录。', 'success');
      } else {
        proxy.$message.error(res.message);
      }
    });
  };
</script>

<style lang="less" scoped>
  .el-header {
    display: flex;
    justify-content: space-between;
    height: 60px;
    background-color: @background-color-darker;
    line-height: 60px;
  }
  .el-header-title {
    display: inline-block;
    width: 220px;
  }
  .el-header-logo {
    vertical-align: middle;
  }
  .el-menu {
    flex: 1;
    background-color: @background-color-darker !important;
  }
  .el-menu--horizontal .el-menu-item-box {
    display: flex;
  }
  :deep(.el-menu-item),
  :deep(.el-sub-menu__title) {
    width: 130px;
    height: 60px;
    background-color: @background-color-darker !important;
    color: @color-text-regular !important;
    font-size: 16px;
    text-align: center;
    line-height: 60px !important;
    &:hover {
      background-color: rgba(65, 178, 255, 0.8) !important;
    }
  }
  :deep(.el-sub-menu.is-opened .el-sub-menu__title) {
    background-color: rgba(65, 178, 255, 0.8) !important;
  }
  :deep(.el-menu-item.is-active),
  :deep(.el-sub-menu.is-active .el-sub-menu__title) {
    background-color: @color-primary !important;
    color: @color-text-primary !important;
  }
  .el-header-icon {
    display: inline-block;
    width: 20px;
    height: 20px;
    margin-right: 15px;
    background: url('../assets/images/layout/top-nav-icon.png') no-repeat;
  }
  .el-dropdown-link {
    display: flex;
    align-items: center;
    cursor: pointer;
  }
  .el-dropdown-menu {
    width: 140px;
    .tc;
    .el-dropdown-menu__item {
      line-height: 35px;
    }
  }
</style>
